package com.yc.favorite.biz;

import com.yc.favorite.bean.Favorite;
import com.yc.favorite.bean.Tag;
import com.yc.favorite.mapper.FavoriteMapper;
import com.yc.favorite.mapper.TagFavoriteMapper;
import com.yc.favorite.mapper.TagMapper;
import com.yc.favorite.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

public class FavBizImpl implements FavBiz{

    @Override
    public void addFov(Favorite favorite) {
        SqlSession session = MyBatisHelper.openSession();
        try{
            TagMapper tm = session.getMapper(TagMapper.class);
            FavoriteMapper fm = session.getMapper(FavoriteMapper.class);
            TagFavoriteMapper tfm = session.getMapper(TagFavoriteMapper.class);
            // 省略字段验证
            // 保存连接
            fm.insert(favorite);
            // 分析 frags 字段 : 门户,新闻,体育
            String[] tags = favorite.getFtags().split("[,，；\\-;\\s]+");

            for (String tag : tags){
                if (tm.updateCount(tag) == 0){
                    Tag t = new Tag();
                    t.setTname(tag);
                    t.setTcount(1);
                    // 新增分类
                    tm.insert(t);
                    // 新增中间表记录
                    tfm.insert(t.getTid(), favorite.getFid());
                } else {
                    // 新增中间表记录
                    tfm.insertByTname(tag, favorite.getFid());
                }
            }
            session.commit();
        } catch (Exception e){
            e.printStackTrace();
            session.rollback();
        } finally {
            session.close();
        }
    }

}
